#include <iostream>
#include <unistd.h>
#include <string>
#include <pthread.h>

int tickets = 1000;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *start_routine(void *args)
{
    std::string name = static_cast<const char *>(args);

    while (1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex); // 为什么要有mutex
        if (tickets > 0)
        {
            std::cout << name << " -> " << tickets << std::endl;
            tickets--;
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }

        usleep(1000);
    }

    std::cout<<" 这里 "<<std::endl;

    return nullptr;
}

int main()
{
    pthread_t t[5];

    for (int i = 0; i < 5; i++)
    {
        char *name = new char[64];
        snprintf(name, 64, "thread - %d", i + 1);
        pthread_create(t + i, nullptr, start_routine, name);
    }

    while (1)
    {
        usleep(100);
        std::cout << "main thread weakup one thread..." << std::endl;
        pthread_mutex_lock(&mutex);
        if (tickets > 0)
        {
            pthread_cond_signal(&cond);
        }
        else
        {
            pthread_cond_broadcast(&cond);
            pthread_mutex_unlock(&mutex);
            break;
        }
        pthread_mutex_unlock(&mutex);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_join(t[i], nullptr);
    }

    return 0;
}
